package com.lkd.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.security.auth.login.LoginException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao,TaskEntity> implements TaskService{

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private MqttProducer mqttProducer;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(innerCode)){
            qw.eq(TaskEntity::getInnerCode,innerCode);
        }
        if(userId != null && userId > 0){
            qw.eq(TaskEntity::getUserId,userId);
        }
        if(!Strings.isNullOrEmpty(taskCode)){
            qw.like(TaskEntity::getTaskCode,taskCode);
        }
        if(status != null && status > 0){
            qw.eq(TaskEntity::getTaskStatus,status);
        }
        if(isRepair != null){
            if(isRepair){
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }else {
                qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if(!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)){
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime,LocalDate.parse(end,DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page,qw));
    }



    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId,VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }


    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    /**
     * 创建工单
     *
     * @param taskViewModel
     * @return
     */
    @Override
    public boolean create(TaskViewModel taskViewModel) throws LogicException{


        checkCreateTask(taskViewModel.getInnerCode(),taskViewModel.getProductType());
        if(hasTask(taskViewModel.getInnerCode(),taskViewModel.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }

        //新增工单表记录
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setTaskCode(generateTaskCode());//工单编号
        BeanUtils.copyProperties(taskViewModel,taskEntity);//复制属性
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        taskEntity.setProductTypeId(taskViewModel.getProductType());
        //跨服务查询售货机微服务，得到售货机的地址和区域id
        VmVO vm = vmService.getVMInfo(taskViewModel.getInnerCode());
        taskEntity.setAddr(vm.getNodeAddr());
        taskEntity.setRegionId(  vm.getRegionId() );
        this.save(taskEntity);

        //如果是补货工单，向 工单明细表插入记录
        if(taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
            taskViewModel.getDetails().forEach(d->{
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties( d,detailsEntity );
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }

        //如果是投放工单或撤机工单
        if(taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_DEPLOY
                || taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_REVOKE){
            noticeVMServiceStatus(taskEntity);//运维工单封装与下发
        }

        //如果是补货工单!!!!---------------------------
        if(taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_SUPPLY){
            noticeVMServiceSupply(taskEntity);
        }

        updateTaskZSet(taskEntity,1);


        return true;
    }

    /**
     * 接收工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean accept(Long id) {
        TaskEntity task = this.getById(id);
        if (task.getTaskStatus() != VMSystem.TASK_STATUS_CREATE){
                throw new LogicException("工单状态不是待处理");
        }
        //修改工单状态为进行
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        return this.updateById(task);
    }

    /**
     * 取消工单
     *
     * @param id
     * @param cancelVm
     * @return
     */
    @Override
    public boolean cancel(Long id, CancelTaskViewModel cancelVm) {

        TaskEntity task = this.getById(id);
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL){
            throw new LogicException("工单已经结束");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL); //修改工单状态取消
        task.setDesc(cancelVm.getDesc());
        //
        updateTaskZSet(task,-1);
        return this.updateById(task);
    }

    /**
     * 完成工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean complete(Long id) {
        TaskEntity taskEntity = this.getById(id);
        if (taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || taskEntity.getTaskStatus() ==VMSystem.TASK_STATUS_CANCEL){
            throw new LogicException("工单已经结束");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH); //修改工单状态完成
        this.updateById(taskEntity);
        //如果是投放工单或撤机工单
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_DEPLOY || taskEntity.getProductTypeId() ==VMSystem.TASK_TYPE_REVOKE){
            noticeVMServiceStatus(taskEntity); //运维工单封装与下发
        }
        //如果是补货工单
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
            noticeVMServiceSupply(taskEntity);
        }
        return true;
    }



    private void noticeVMServiceStatus(TaskEntity taskEntity) {
        //向消息队列发送消息,通过售货机更新状态
        //封装协议
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        taskCompleteContract.setInnerCode(taskEntity.getInnerCode());  //售货机编号
        taskCompleteContract.setTaskType(taskEntity.getProductTypeId()); // 工单类型
        //发送到emq
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC,2,taskCompleteContract);
        } catch (Exception e) {
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单协议出错");
        }

    }

    /**
     * 补货协议封装与下发
     * @param taskEntity
     */
    private void noticeVMServiceSupply(TaskEntity taskEntity){
        QueryWrapper<TaskDetailsEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(TaskDetailsEntity::getTaskId,taskEntity.getTaskId());
        List<TaskDetailsEntity> detalist = taskDetailsService.list(qw);
        //构造协议内容
        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setInnerCode(taskEntity.getInnerCode()); //售货机编号
        List<SupplyChannel> supplyChannels = Lists.newArrayList();  //补货数据
        //从工单明细表提取数据加到补货数据中
        detalist.forEach(d ->{
            SupplyChannel channel = new SupplyChannel();
            channel.setChannelId(d.getChannelCode());  //货道编号
            channel.setCapacity(d.getExpectCapacity()); //补货数量
            supplyChannels.add(channel);
        });
        supplyContract.setSupplyData(supplyChannels);
        //下发补货协议
        //发送到emq
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC,2,supplyContract);
        } catch (Exception e) {
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }
    }

    /**
     * 生成工单编号
     * @return
     */
    private String generateTaskCode(){
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key= "lkd.task.code."+date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if(obj==null){
            redisTemplate.opsForValue().set(key,1L, Duration.ofDays(1) );
            return date+"0001";
        }
        return date+  Strings.padStart( redisTemplate.opsForValue().increment(key,1).toString(),4,'0');
    }

    private void checkCreateTask(String innerCode,int productType) throws LogicException{
        //根据设备编号查询设备
        VmVO vmInfo = vmService.getVMInfo(innerCode);
        if (vmInfo == null){
            throw new LogicException("设备校验失败");
        }
        //投放工单,售货状态为运营
        if (productType == VMSystem.TASK_TYPE_DEPLOY &&  vmInfo.getVmStatus() == VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("设备正在运营");
        }

        //补货工单,!=1,售货状态不运营
        if (productType == VMSystem.TASK_TYPE_SUPPLY &&  vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("该设备不在运营状态");
        }
        //撤机工单,!=1售货状态不运营
        if (productType == VMSystem.TASK_TYPE_REPAIR &&  vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("该设备不在运营状态");
        }
        //撤机工单,!=1售货状态不运营
        if (productType == VMSystem.TASK_TYPE_REVOKE &&  vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("该设备不在运营状态");
        }
    }

    /**
     * 同一台设备下是否存在未完成的工单
     * @param innerCode
     * @param productionType
     * @return
     */
    private boolean hasTask(String innerCode,int productionType){
        LambdaQueryWrapper<TaskEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(TaskEntity::getTaskId)
                    .eq(TaskEntity::getTaskCode,innerCode)
                    .eq(TaskEntity::getProductTypeId,productionType)
                    .le(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_PROGRESS);
        return this.count(queryWrapper)>0;
    }

    /**
     * 获取同一天内分配的工单最少的人
     *
     * @param regionId
     * @param isRepair 是否是运维工单
     * @return
     */
    @Override
    public int getLeastUser(Long regionId, Boolean isRepair) {
        String roleCode = "1002";
        if (isRepair){     //如果是运维人员
            roleCode = "1003";      //运维人员

        }
        String key = VMSystem.REGION_TASK_KEY_PREF
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                +"." + regionId + "." + roleCode;
        Set<Object> set = redisTemplate.opsForZSet().range(key, 0, 0);//取第1个
        if (set == null || set.isEmpty()) {
            return  0;      //如果没有数据返回0
        }

        return (Integer) set.stream().collect(Collectors.toList()).get(0);
    }

    public void updateTaskZSet(TaskEntity taskEntity, int score){
        String roleCode="1003";//运维员
        if(taskEntity.getProductTypeId().intValue()==2){//如果是补货工单
            roleCode="1002";//运营员
        }
        String key= VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                +"."+ taskEntity.getRegionId()+"."+roleCode;
        redisTemplate.opsForZSet().incrementScore(key,taskEntity.getUserId(),score);
    }
}
